package com.cater.task.controller;

import java.io.File;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.cater.annotation.SystemControllerLog;
import com.cater.common.PageResult;
import com.cater.common.UserContext;
import com.cater.query.CommonQuery;
import com.cater.sys.entity.Dictionarydata;
import com.cater.sys.service.UserService;
import com.cater.sys.service.impl.DictionarydataServiceImpl;
import com.cater.task.entity.TaskCompletion;
import com.cater.task.entity.TaskManager;
import com.cater.task.service.TaskCompletionServiceImpl;
import com.cater.task.service.TaskManagerServiceImpl;

/**
 * 描述：任务控制层
 * 
 * @author yong
 * @date 2018/06/03
 */
@Controller
@RequestMapping("/taskManager")
public class TaskManagerController {

	@Autowired
	private TaskManagerServiceImpl service;
	@Autowired
	private DictionarydataServiceImpl dictService;// 数据字典
	@Autowired
	private UserService userService;// 用户
	@Autowired
	private TaskCompletionServiceImpl taskCompletionService;// 任务完成情况

	/**
	 * @任务管理列表视图
	 * @return
	 */
	@RequestMapping("/list")
	public String list() {
		return "task/taskManager/list";
	}

	/**
	 * @任务管理数据分页
	 * @param query
	 * @param request
	 * @return
	 */
	@RequestMapping("listData")
	@ResponseBody
	@SystemControllerLog(description = "查询任务分页数据")
	public PageResult<TaskManager> listData(CommonQuery query, HttpServletRequest request) {
		Integer userid = UserContext.getId();
		query.setPrincipal(userid);
		PageResult<TaskManager> result = service.findPageResult(query);
		Dictionarydata dict = null;
		Dictionarydata dictStatus = null;
		String user_name = "";
		for (TaskManager t : result.getRows()) {
			String degree = t.getUrgency();
			String status = String.valueOf(t.getStatus());
			if (StringUtils.isNotEmpty(degree)) {
				dict = dictService.getByTypeValue(degree, "task_urgency");
				dictStatus = dictService.getByTypeValue(status, "task_status");
				if (dict != null) {
					t.setDictDegree(dict.getValueName());
				} else {
					t.setDictDegree("暂无");
				}
				if (dictStatus != null) {
					t.setDictStatus(dictStatus.getValueName());
				} else {
					t.setDictStatus("暂无");
				}
			}
			String user_ids[] = t.getParticipant().split(",");
			user_name = getUserNames(user_ids);
			if (StringUtils.isNotEmpty(user_name)) {
				t.setUserNames(user_name);
			} else {
				t.setUserNames("暂无");
			}
		}
		return result;
	}

	/**
	 * 添加视图
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "addView")
	@RequiresPermissions("taskManager:add")
	public String addView() {
		return "task/taskManager/add";
	}

	/**
	 * 添加操作
	 * 
	 * @param t
	 * @return
	 */
	@RequestMapping(value = "add")
	@RequiresPermissions("taskManager:add")
	@ResponseBody
	@SystemControllerLog(description = "添加任务")
	public JSONObject add(TaskManager t, CommonQuery query) {
		JSONObject json = new JSONObject();
		String id = service.saves(t);
		if (StringUtils.isNotBlank(id)) {
			json.put("code", 200);
			json.put("message", "success");
		} else {
			json.put("code", 999);
			json.put("message", "fail");
		}
		return json;
	}

	/**
	 * 修改视图
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "editView")
	@RequiresPermissions("taskManager:edit")
	public String editView(String id, Model model, CommonQuery query) {
		TaskManager t = service.getById(id);
		String user_ids[] = t.getParticipant().split(",");
		String user_name = getUserNames(user_ids);
		if (StringUtils.isNotEmpty(user_name)) {
			t.setUserNames(user_name);
		} else {
			t.setUserNames("暂无");
		}
		model.addAttribute("taskManager", t);
		return "task/taskManager/update";
	}

	/**
	 * 修改操作
	 * 
	 * @param t
	 * @return
	 */
	@RequestMapping(value = "update")
	@RequiresPermissions("taskManager:edit")
	@ResponseBody
	@SystemControllerLog(description = "修改任务")
	public JSONObject update(TaskManager t, CommonQuery query) {
		JSONObject json = new JSONObject();
		try {
			service.update(t);
			json.put("code", 200);
			json.put("message", "修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "修改失败");
		}
		return json;
	}

	/**
	 * 删除操作
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delete")
	@RequiresPermissions("taskManager:delete")
	@SystemControllerLog(description = "删除任务")
	public JSONObject delete(String id) {
		JSONObject json = new JSONObject();
		try {
			service.delete(id);
			json.put("code", 200);
			json.put("message", "删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "删除失败");
		}
		return json;
	}

	@RequestMapping("/getByid")
	@ResponseBody
	public JSONObject getByid(String id, CommonQuery query) {
		JSONObject json = new JSONObject();
		TaskManager taskManager = service.getById(id);
		json.put("taskManager", taskManager);
		return json;
	}

	@ResponseBody
	@RequestMapping("/deletePic")
	public JSONObject deletePic(String id, String picUrl, HttpServletRequest request) {
		JSONObject json = new JSONObject();
		TaskManager taskManagerProduce = new TaskManager();
		String filePath = request.getSession().getServletContext().getRealPath("/");
		try {
			taskManagerProduce = service.getById(id);
			String testpic = taskManagerProduce.getFileNames().replace(picUrl + ",", "");
			taskManagerProduce.setFileNames(testpic);
			service.update(taskManagerProduce);
			File file = new File(filePath + picUrl);
			if (file.exists() && file.isFile()) {
				file.delete();
				json.put("code", 200);
				json.put("message", "删除成功");
			} else {
				json.put("code", 999);
				json.put("message", "删除失败或不存在");
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "删除失败");
		}
		return json;
	}

	/**
	 * 修改视图
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "progressView")
	@RequiresPermissions("taskManager:progress")
	public String progressView(String id, Model model, CommonQuery query) {
		TaskManager t = service.getById(id);
		String user_ids[] = t.getParticipant().split(",");
		String user_name = getUserNames(user_ids);
		if (StringUtils.isNotEmpty(user_name)) {
			t.setUserNames(user_name);
		} else {
			t.setUserNames("暂无");
		}
		model.addAttribute("taskManager", t);
		return "task/taskManager/task_progress";
	}

	/**
	 * 添加任务进度
	 * 
	 * @param t
	 * @param query
	 * @return
	 */
	@RequestMapping(value = "progress")
	@RequiresPermissions("taskManager:progress")
	@ResponseBody
	@SystemControllerLog(description = "添加任务进度")
	public JSONObject progress(TaskManager t, CommonQuery query) {
		JSONObject json = new JSONObject();
		try {
			TaskManager taskManager = service.getById(t.getId());
			taskManager.setPlan(t.getPlan());
			taskManager.setFileNames(t.getFileNames());
			service.update(taskManager);
			json.put("code", 200);
			json.put("message", "进度添加成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "进度添加失败");
		}
		return json;
	}

	/**
	 * 查看视图
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "detailView")
	@RequiresPermissions("taskManager:detail")
	public String detailView(String id, Model model, CommonQuery query) {
		TaskManager t = service.getById(id);
		String user_ids[] = t.getParticipant().split(",");
		String user_name = getUserNames(user_ids);
		if (StringUtils.isNotEmpty(user_name)) {
			t.setUserNames(user_name);
		} else {
			t.setUserNames("暂无");
		}
		List<TaskCompletion> taskCompletions = taskCompletionService.getByTaskId(id);
		if (taskCompletions.size() > 0) {
			model.addAttribute("taskCompletions", taskCompletions);
		}
		model.addAttribute("taskManager", t);
		return "task/taskManager/detail";
	}

	private String getUserNames(String[] user_ids) {
		String user_name = "";
		try {
			if (user_ids.length != 0) {
				List<Map<String, String>> users = userService.getByArrIds(user_ids);
				Integer num = 1;
				if (users.size() > 0) {
					for (Map<String, String> map : users) {
						if (num == users.size()) {
							user_name += map.get("truename");
						} else {
							user_name += map.get("truename") + " | ";
						}
						num++;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user_name;
	}

	@RequestMapping("/statusView")
	public String statusView(String id, Model model) {
		TaskManager t = service.getById(id);
		model.addAttribute("taskManager", t);
		return "task/taskManager/update_status";
	}

	@ResponseBody
	@RequestMapping("/updateStatus")
	public JSONObject updateStatus(String id, Integer status) {
		JSONObject json = new JSONObject();
		TaskManager t = service.getById(id);
		if (t != null) {
			t.setStatus(status);
			try {
				service.update(t);
				json.put("code", 200);
				json.put("message", "状态修改成功");
			} catch (Exception e) {
				e.printStackTrace();
				json.put("code", 400);
				json.put("message", "状态修改失败");
			}
		}
		return json;

	}
}